<?php

namespace App\Console\Commands\Shop;

use App\Kuafu\Shop\Enum\AreaCodeEnum;
use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Model\AreaModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopAttributeCategoryModel;
use App\Kuafu\Shop\Model\ShopAttributeMappingModel;
use App\Kuafu\Shop\Model\ShopAttributeModel;
use App\Kuafu\Shop\Service\ShopAttributeService;
use App\Remote\Tiger\OpenShop\OpenShopRemote;
use Illuminate\Console\Command;

class InitShopAttributeMapping extends Command
{
    protected $signature = 'shop:initShopAttributeMapping';

    protected $description = '初始化门店属性值';

    public function handle()
    {
        // 门店属性值列表
        $shopAttributeList = ShopAttributeModel::query()->get();

        // 售卖品类  多选 炸串 炸鸡 主食 包装饮品 景区精选
        $sellAttributeData = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_4)->values()
            ->first();

        // 城市分级  单选 一线 二线 三线 四线 五线
        $cityGradeAttributeData = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_16)->values()
            ->toArray();

        // 产品定价 单选 A级(一线+西藏) B级(新一/二/三线城市) C级(四/五线) S级(精选产品特殊定价) 其他
        $cityMenuLevelAttributeData = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_11)->values()
            ->toArray();

        // 收银设备 单选 夸父收银 美团收银 其他收银
        $cashTypeData = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_14)->values()
            ->toArray();

        // 门店状态 选址中 筹备中 正常营业 暂停营业 闭店
        $shopStatus = $shopAttributeList->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_12)
                                        ->map(function ($item) {
                                            return [
                                                'id'   => $item->id,
                                                'name' => $item->name,
                                            ];
                                        })->keyBy('name')->toArray();

        // 城市对应
        $areaData   = AreaModel::query()
                               ->where('level', AreaCodeEnum::AREA_CITY)
                               ->get()->keyBy('areaId')->toArray();
        $createData = [];
        Shop::query()
            ->whereIn('status', [CodeEnum::SHOP_STATUS_NORMAL, CodeEnum::SHOP_STATUS_PREPARE])//启用+筹备中
            ->chunkById(500, function ($shops) use (
                $cityGradeAttributeData,
                $cityMenuLevelAttributeData,
                $areaData,
                $shopAttributeList,
                $sellAttributeData,
                $shopStatus,
                $cashTypeData,
                &$createData
            ) {
                $shopIds  = array_column($shops->toArray(), 'id');
                /*$shopList = collect(OpenShopRemote::getShopAttributeByShopIds($shopIds, 'guanyuan') ?? [])// 观远数据
                ->keyBy('id')
                ->toArray();
                if ($shopList) {
                    foreach ($shopList as $shop) {
                        if (in_array($shop['status'], ['选址中', '筹备中', '正常营业', '暂停营业', '闭店'])) {
                            $newId = $shopStatus[$shop['status']]['id'] ?? 0;// 当前状态对应属性id
                            if ($newId) {
                                $createData[] = [
                                    'shopId'      => $shop['id'],
                                    'attributeId' => $newId,
                                    'value'       => '',
                                    'createdAt'   => time(),
                                ];
                            }
                        } elseif ($shop['status'] == '迁址中') {

                            // 迁址状态  单选 是 or 否
                            $relocationStatus = $shopAttributeList
                                ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_13)
                                ->where('name', '是')->first();
                            if ($relocationStatus) {
                                $createData[] = [
                                    'shopId'      => $shop['id'],
                                    'attributeId' => $relocationStatus->id,
                                    'value'       => '',
                                    'createdAt'   => time(),
                                ];
                            }
                        }
                        if ($shop['cashierSystem']) {
                            if ($shop['cashierSystem'] == '第三方') {
                                $shop['cashierSystem'] = '其他收银';
                            }
                            foreach ($cashTypeData as $cashType) {
                                if (strpos($cashType['name'], $shop['cashierSystem']) !== false) {
                                    $createData[] = [
                                        'shopId'      => $shop['id'],
                                        'attributeId' => $cashType['id'],
                                        'value'       => '',
                                        'createdAt'   => time(),
                                    ];
                                    break;
                                }
                            }
                        }
                    }
                }*/

                $shopList = collect(OpenShopRemote::getShopAttributeByShopIds($shopIds, '') ?? [])// 开店选址数据
                ->keyBy('shopId')
                ->toArray();
                if ($shopList) {
                    foreach ($shopList as $shop) {
                        $engineeringExhibitionArea = $shop['engineeringExhibitionArea'] ?? 0;// 工程条件-展面
                        if ($engineeringExhibitionArea) {
                            $engineeringExhibitionAreaId = ShopAttributeService::getShopAttributeByRange($shopAttributeList->toArray(),
                                ShopAttributeCategoryModel::CATEGORY_ID_7, (int)$engineeringExhibitionArea);
                            $createData[]                = [
                                'shopId'      => $shop['shopId'],
                                'attributeId' => $engineeringExhibitionAreaId,
                                'value'       => $engineeringExhibitionArea,
                                'createdAt'   => time(),
                            ];
                        }

                        $engineeringArea = $shop['engineeringArea'] ?? 0;// 工程条件-面积
                        if ($engineeringArea) {
                            $engineeringAreaId = ShopAttributeService::getShopAttributeByRange($shopAttributeList->toArray(),
                                ShopAttributeCategoryModel::CATEGORY_ID_8, (int)$engineeringArea);
                            $createData[]      = [
                                'shopId'      => $shop['shopId'],
                                'attributeId' => $engineeringAreaId,
                                'value'       => $engineeringArea,
                                'createdAt'   => time(),
                            ];
                        }
                        $engineeringElectricity = $shop['engineeringElectricity'] ?? 0;// 工程条件-电量
                        if ($engineeringElectricity) {
                            $engineeringElectricityId = ShopAttributeService::getShopAttributeByRange($shopAttributeList->toArray(),
                                ShopAttributeCategoryModel::CATEGORY_ID_10, (int)$engineeringElectricity);
                            $createData[]             = [
                                'shopId'      => $shop['shopId'],
                                'attributeId' => $engineeringElectricityId,
                                'value'       => $engineeringElectricity,
                                'createdAt'   => time(),
                            ];
                        }
                        $engineeringDepth = $shop['engineeringDepth'] ?? 0;// 工程条件-进深
                        if ($engineeringDepth) {
                            $engineeringDepthId = ShopAttributeService::getShopAttributeByRange($shopAttributeList->toArray(),
                                ShopAttributeCategoryModel::CATEGORY_ID_9, (int)$engineeringDepth);
                            $createData[]       = [
                                'shopId'      => $shop['shopId'],
                                'attributeId' => $engineeringDepthId,
                                'value'       => $engineeringDepth,
                                'createdAt'   => time(),
                            ];
                        }
                    }
                }

                /*foreach ($shops as $shop) {
                    dump($shop['id'], $shop['name']);
                    $attributeId = $shop['type'] ?? 0;// 门店性质 单选 加盟店 直营店
                    if ($attributeId) {
                        $createData[] = [
                            'shopId'      => $shop['id'],
                            'attributeId' => $attributeId,
                            'value'       => '',
                            'createdAt'   => time(),
                        ];
                    }

                    // 售卖品类 炸串
                    if ($sellAttributeData) {
                        $createData[] = [
                            'shopId'      => $shop['id'],
                            'attributeId' => $sellAttributeData->id,
                            'value'       => '',
                            'createdAt'   => time(),
                        ];
                    }

                    $city = $shop['city'] ?? 0;// 城市code
                    if ($city) {
                        $categoryId   = ShopAttributeCategoryModel::CATEGORY_ID_17;// 城市
                        $attribute    = $shopAttributeList->where('categoryId', $categoryId)->first();
                        $createData[] = [
                            'shopId'      => $shop['id'],
                            'attributeId' => $attribute->id,
                            'value'       => $city,
                            'createdAt'   => time(),
                        ];

                        // 城市分级
                        $cityGrade = $areaData[$city]['grade'] ?? 0;// 城市分级
                        $newId     = $cityGradeAttributeData[$cityGrade - 1]['id'] ?? 0;
                        if ($newId) {
                            $createData[] = [
                                'shopId'      => $shop['id'],
                                'attributeId' => $newId,
                                'value'       => '',
                                'createdAt'   => time(),
                            ];
                        }

                        // 产品定价 菜单等级
                        $cityMenuLevel = ShopAttributeService::getMenuLevel($areaData[$city]['menuLevel'] ?? '');// 产品定价
                        $newId         = $cityMenuLevelAttributeData[$cityMenuLevel - 1]['id'] ?? 0;
                        if ($newId) {
                            $createData[] = [
                                'shopId'      => $shop['id'],
                                'attributeId' => $newId,
                                'value'       => '',
                                'createdAt'   => time(),
                            ];
                        }
                    }

                    // 迁址状态  单选 是 or 否
                    $relocationStatus = $shopAttributeList
                        ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_13)
                        ->where('name', '是')->first();
                    $isExist          = ShopAttributeMappingModel::getData($shop['id'], $relocationStatus->id);
                    if (!$isExist) {
                        $relocationStatus = $shopAttributeList
                            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_13)
                            ->where('name', '否')->first();
                        if ($relocationStatus) {
                            $createData[] = [
                                'shopId'      => $shop['id'],
                                'attributeId' => $relocationStatus->id,
                                'value'       => '',
                                'createdAt'   => time(),
                            ];
                        }
                    }
                }*/
            });

        if ($createData) {
//            ShopAttributeMappingModel::query()->truncate();
            $chunk = array_chunk($createData, 500);
            foreach ($chunk as $value) {
                ShopAttributeMappingModel::query()->insert($value);
            }
        }
    }
}
